<?php
class FavoriteSeller extends AppModel{
    var $name = 'FavoriteSeller';
    var $belongsTo = array(
		'User' => array(
			'className' => 'User',
			'foreignKey' => 'seller_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
        );
    var $hasMany=array('FavouriteNote'=>array(
                    'className' => 'FavouriteNote',
                    'foreignKey' => 'favorite_sellers_id'
                ));

        function insertFavorite($userId){
            App::import('model', 'Order');
            App::import('model', 'Subscribe');
            $or=new Order;
            $sub= new Subscribe;
            //pr($or->find('all', array('conditions'=>array('Orders.user_id'=>$userId, 'DATE_SUB(CURDATE(),INTERVAL 1 DAY) <='=>'Orders.add_date'))));
            $allOrders=$or->find('all', array('conditions'=>array('Orders.user_id'=>$userId, 'DATE_SUB(CURDATE(),INTERVAL 90 DAY) <'=>'Orders.add_date'), 'limit'=>'100'));
            
            foreach($allOrders as $allOrder){
                $order[]=$allOrder['Orders']['user_id'];
            }
            $orders=array_unique($order);
            foreach($orders as $order){
                $this->data['FavoriteSeller']['seller_id']=$order;
                $this->data['FavoriteSeller']['buyer_id']=$userId;
                $this->data['FavoriteSeller']['id']=NULL;

                $this->save($this->data);
                
               //insert subscription
               $this->data['Subscribe']['seller_id']=$order;
               $this->data['Subscribe']['buyer_id']=$userId;
               $this->data['Subscribe']['period']=30;
               $this->data['Subscribe']['id']=NULL;
               $sub->save($this->data);
            }
        }

        function allFavorites($userId){
            App::import('model', 'Subscribe');
            App::import('model', 'MessageTrack');

            $sub=new Subscribe();
            $msg=new MessageTrack();
            $i=0;
            
            $favorites=$this->find('all', array('conditions'=>array('FavoriteSeller.buyer_id'=>$userId)));
            foreach ($favorites as $fav){
                $subs=$sub->find('first', array('conditions'=>array('Subscribe.seller_id'=>$fav['FavoriteSeller']['seller_id'], 'Subscribe.buyer_id'=>$userId)));
                
                $msgs=$msg->lastMsg($userId, $fav['FavoriteSeller']['seller_id']);
                
                $favorites[$i]['subs']=$subs;
                $favorites[$i]['lastMassegeRecive']=$msgs;
                $i++;
            }
            return $favorites;

        }
}
